import { EventMsg } from "../DataCenter/GlobalContext";

export default class EventManager {
    private static instance: EventManager = null;
    /**
     * 事件缓存
     */
    private event_cache: Map<EventMsg, Function[]> = null;
    private target_cache: Map<EventMsg, any[]> = null;
    public static getInst(): EventManager {
        if (this.instance == null) {
            this.instance = new EventManager();
            this.instance.event_cache = new Map<EventMsg, Function[]>();
            this.instance.target_cache = new Map<EventMsg, any[]>();
        }
        return this.instance;
    }

    /**
     * 事件注册
     * @param eventMsg 
     * @param callback 
     */
    On(eventMsg: EventMsg, callback: Function, target: any) {
        if (!this.event_cache.has(eventMsg)) {
            this.event_cache.set(eventMsg, []);
            this.target_cache.set(eventMsg, []);
        }
        this.event_cache.get(eventMsg).push(callback);
        this.target_cache.get(eventMsg).push(target);
    }

    /**
     * 触发事件
     * @param eventMsg 
     * @param param 
     * @returns 
     */
    Trigger(eventMsg: EventMsg, param: any = null) {
        if (!this.event_cache.has(eventMsg)) {
            return;
        }
        
        const callbacks: Function[] = this.event_cache.get(eventMsg);
        const targets: any[] = this.target_cache.get(eventMsg);
        for (let i = 0; i < callbacks.length; i++)
            callbacks[i].call(targets[i], param);
    }

    /**
     * 事件移除
     * @param eventMsg 
     * @param callback 
     */
    Un(eventMsg: EventMsg, callback: Function) {
        if (this.event_cache.has(eventMsg)) {
            let callbacks = this.event_cache.get(eventMsg);
            const targets = this.target_cache.get(eventMsg);
            for (let i = callbacks.length - 1; i >= 0; i--) {
                if (callbacks[i] === callback) {
                    callbacks.splice(i, 1);
                    targets.slice(i, 1);
                }
            }
        }
    }

    /**
     * 移除
     */
    UnKey(){

    }

    /**
     * 清空事件
     */
    clear() {
        if (this.event_cache) {
            this.event_cache.clear();
        }
    }
}